package qianlong.practice.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import qianlong.practice.entity.User;
import qianlong.practice.service.UserService;
import qianlong.practice.util.PageUtil;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    //列表 + 查询 + 分页  ===> PageHelper (mybatis)
    @RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
    public String list(@ModelAttribute("user") User user,
                       @ModelAttribute("page") PageUtil page,
                       String start_age, String end_age, ModelMap model) {
        user.getDataMap().put("name", user.getName()); //like
        user.setName(null);
        user.getDataMap().put("start_age", start_age); //between ... and ...
        user.getDataMap().put("end_age", end_age);
        page.init(page.getRequestPage(), page.getPageSize(), userService.getCount(user));
        user.getDataMap().put("limit", page.getLimit()); //limit 0,10
        user.getDataMap().put("offset", page.getOffset());
        log.info("==============>limit:{}",page.getLimit());
        log.info("==============>offset:{}",page.getOffset());

        model.addAttribute("userList",userService.getPage(user));
        return "user/list";
    }

    //进入添加 / 修改 页面
    @RequestMapping(value = "/input", method = {RequestMethod.GET})
    public String input(@RequestParam(required = false)Integer id, ModelMap model) {
        if(id != null && id != 0){model.addAttribute("user",userService.getOne(id));}
        return "user/input";
    }

    //添加保存 + 修改保存
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public String save(@ModelAttribute("user") User user) {
        int result = user.getId() != null && user.getId() != 0 ? userService.update(user) : userService.insert(user);
        return "redirect:list";
    }

    //删除保存
    @RequestMapping(value = "/delete", method = {RequestMethod.GET})
    public String delete(@RequestParam(required = true)Integer id) {
        if(id != null && id != 0){userService.delete(id);}
        return "redirect:list";
    }
}